<?php
declare(strict_types=1);

namespace app\middleware;

use app\model\Role;
use think\facade\Log;

class Permission
{
    public function handle($request, \Closure $next)
    {
        try {
            // 获取当前路由
            $path = $request->pathinfo();
            
            // 获取用户角色
            $roleId = $request->adminInfo['role_id'];
            $role = Role::find($roleId);
            if (!$role) {
                return json(['code' => 403, 'msg' => '无权限访问']);
            }
            
            // 获取角色权限
            $permissions = json_decode($role->permissions, true);
            if (!$permissions) {
                return json(['code' => 403, 'msg' => '无权限访问']);
            }
            
            // 检查权限
            $hasPermission = false;
            foreach ($permissions as $permission) {
                if ($this->checkPermission($permission, $path)) {
                    $hasPermission = true;
                    break;
                }
            }
            
            if (!$hasPermission) {
                return json(['code' => 403, 'msg' => '无权限访问']);
            }
            
            return $next($request);
        } catch (\Exception $e) {
            Log::error('权限验证失败: ' . $e->getMessage());
            return json(['code' => 500, 'msg' => '系统错误']);
        }
    }
    
    /**
     * 检查权限
     */
    protected function checkPermission($permission, $path)
    {
        // 检查当前路径是否匹配权限配置的path
        if (isset($permission['path']) && $permission['path'] == $path) {
            return true;
        }
        
        // 检查子权限
        if (isset($permission['children'])) {
            foreach ($permission['children'] as $child) {
                if ($this->checkPermission($child, $path)) {
                    return true;
                }
            }
        }
        
        return false;
    }
} 